package com.huibo.aigou.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.huibo.aigou.base.bo.AjaxResult;
import com.huibo.aigou.base.bo.PageObj;
import com.huibo.aigou.base.bo.PageQuery;
import com.huibo.aigou.base.util.LetterUtil;
import com.huibo.aigou.base.util.StrUtils;
import com.huibo.aigou.domain.Brand;
import com.huibo.aigou.service.BrandService;

@RestController
@RequestMapping("/brand")
public class BrandController {

	@Autowired
	private BrandService brandService;
	
	@GetMapping("/get/{id}")
	public Brand get(@PathVariable(value="id",required=true) Long id) {
		Brand brand = brandService.getById(id);
		return brand;
	}
	
	@PostMapping("/list")
	public PageObj<Brand> list(@RequestBody PageQuery pageQuery) {
		return brandService.pageList(pageQuery);
	}
	
	@DeleteMapping("/deleteBatch")
	public AjaxResult deleteBatch(String ids) {
		List<Long> listIds = StrUtils.splitStr2LongArr(ids);
		try {
			brandService.removeByIds(listIds);
			return AjaxResult.createInstance().setMsg("删除成功");
		}catch(Exception e) {
			e.printStackTrace();
			return AjaxResult.createInstance().setCode(500).setMsg("删除失败");
		}

	}
	
	@PostMapping("/save")
	public AjaxResult save(@RequestBody Brand brand) {
		try {
			if(brand.getId() == null) {
				brand.setCreateTime(System.currentTimeMillis());
				String firstLetter = LetterUtil.getFirstLetter(brand.getName());
				brand.setFirstLetter(firstLetter.toUpperCase());
				brandService.save(brand);
			} else {
				brand.setUpdateTime(System.currentTimeMillis());
				brandService.updateById(brand);
			}
			return AjaxResult.createInstance().setCode(200);
		} catch(Exception e) {
			e.printStackTrace();
			return AjaxResult.createInstance().setCode(500).setMsg("保存品牌失败");
		}	
	}
	
	@GetMapping("/delete/{id}")
	public AjaxResult delete(@PathVariable(value="id",required=true) Long id) {
		try {
			brandService.removeById(id);
			return AjaxResult.createInstance().setCode(200);
		} catch(Exception e) {
			e.printStackTrace();
			return AjaxResult.createInstance().setCode(500).setMsg("删除失败");
		}	
	}
}
